//
//  MPGLDetailViewController.m
//  mingpianguanli
//
//  Created by ryou on 2021/6/23.
//
#define kMpglItemSpace 20
#define kMpglItemW (kmpglWidth - 2 * kMpglItemSpace)
#define kMpglItemH kMpglItemW * 9 / 16

#import "MPGLDetailViewController.h"
#import <CoreImage/CoreImage.h>
#import <Photos/Photos.h>
#import <AssetsLibrary/AssetsLibrary.h>

@interface MPGLDetailViewController ()
@property(nonatomic,strong)UIImageView *shareImageView;
@end

@implementation MPGLDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self createView];
    // Do any additional setup after loading the view.
    UIBarButtonItem *saveBtn=[[UIBarButtonItem alloc]initWithTitle:@"分享" style:UIBarButtonItemStylePlain target:self action:@selector(saveBtnClick)];
    
    self.navigationItem.rightBarButtonItem=saveBtn;
    
    [self mingpianguanliloadBannerWithSlotID];

    // Do any additional setup after loading the view.
}
-(void)saveBtnClick{
    
    UIImage * image = [self captureImageFromView:self.shareImageView];
    //    ALAssetsLibrary * library = [ALAssetsLibrary new];
    //    NSData * data = UIImageJPEGRepresentation(image, 1.0);
    //    [library writeImageDataToSavedPhotosAlbum:data metadata:nil completionBlock:nil];
    NSString *textToShare1 = @"名片";

    NSArray *activityItems = @[textToShare1, image];
    UIActivityViewController *activityVC = [[UIActivityViewController alloc]initWithActivityItems:activityItems applicationActivities:nil];
    
    //去除一些不需要的图标选项
    activityVC.excludedActivityTypes = @[UIActivityTypePostToFacebook, UIActivityTypeAirDrop, UIActivityTypePostToWeibo, UIActivityTypePostToTencentWeibo];
    
    //成功失败的回调block
    UIActivityViewControllerCompletionWithItemsHandler myBlock = ^(UIActivityType __nullable activityType, BOOL completed, NSArray * __nullable returnedItems, NSError * __nullable activityError) {
        
        if (completed){
            NSLog(@"completed");
        }else{
            NSLog(@"canceled");
        }
    };
    activityVC.completionWithItemsHandler = myBlock;
    
    [self presentViewController:activityVC animated:YES completion:nil];
}
//截图功能

-(UIImage *)captureImageFromView:(UIView *)view{
    UIGraphicsBeginImageContextWithOptions(view.frame.size,NO, 0);
    [[UIColor clearColor] setFill];
    [[UIBezierPath bezierPathWithRect:view.bounds] fill];
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    [view.layer renderInContext:ctx];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */
-(void)createView{
    
    
    UIImageView *mgglBg=[[UIImageView alloc]initWithFrame:CGRectMake(kMpglItemSpace ,100+ kMpglItemSpace , kMpglItemW , kMpglItemH)];
    mgglBg.backgroundColor=[UIColor whiteColor];
    mgglBg.layer.cornerRadius = 10;
    [self.view addSubview:mgglBg];
    _shareImageView = mgglBg;
    
    UILabel *nameLabel=[[UILabel alloc]initWithFrame:CGRectMake(20 ,20,mgglBg.frame.size.width - 40, 30)];
    nameLabel.text = [NSString stringWithFormat:@"名字：%@",self.mpglDict[@"mingzi"]];
    [mgglBg addSubview:nameLabel];
    
    
    UIImageView *mpgllogo=[[UIImageView alloc]initWithFrame:CGRectMake(20, nameLabel.frame.size.height+20, 30, 30)];
    mpgllogo.image=[UIImage imageNamed:@"mpgl_btn_sacn.png"];
    mpgllogo.layer.cornerRadius = 5;
    [mgglBg addSubview:mpgllogo];
    
    UILabel *lianxiLabel=[[UILabel alloc]initWithFrame:CGRectMake(mpgllogo.frame.origin.x + mpgllogo.frame.size.width + 20, nameLabel.frame.size.height+20, mgglBg.frame.size.width - 40 - mpgllogo.frame.size.width, mpgllogo.frame.size.height)];
    lianxiLabel.text = [NSString stringWithFormat:@"%@",self.mpglDict[@"lianxifangshileixing"]];
    [mgglBg addSubview:lianxiLabel];
    
    UILabel *gongsiLabel=[[UILabel alloc]initWithFrame:CGRectMake(20, lianxiLabel.frame.size.height+20+10+lianxiLabel.frame.size.height, mgglBg.frame.size.width - 40 , mpgllogo.frame.size.height)];
    gongsiLabel.text = [NSString stringWithFormat:@"公司：%@ %@",self.mpglDict[@"gongsi"],self.mpglDict[@"zhiwei"]];
    [mgglBg addSubview:gongsiLabel];
    
    
    UILabel *mpgljianjie=[[UILabel alloc]initWithFrame:CGRectMake(20, mpgllogo.frame.size.height+40+gongsiLabel.frame.size.height+lianxiLabel.frame.size.height, mgglBg.frame.size.width - 40 ,gongsiLabel.frame.size.height)];
    mpgljianjie.text = [NSString stringWithFormat:@"简介：%@",self.mpglDict[@"gerenjianjie"]];
    mpgljianjie.numberOfLines=0;
    mpgljianjie.textColor = [UIColor grayColor];
    [mgglBg addSubview:mpgljianjie];
    
    
    UIImageView *erweima=[[UIImageView alloc]initWithFrame:CGRectMake(mgglBg.frame.size.width - 80  - 20, 20, 80, 80)];
    erweima.image=[self createQRCodeWithData:[NSString stringWithFormat:@"%@",self.mpglDict] logoImage:nil imageSize:erweima.frame.size.height];
    erweima.layer.cornerRadius = 5;
    erweima.backgroundColor=[UIColor redColor];
    [mgglBg addSubview:erweima];
    
}


- (UIImage *)createQRCodeWithData:(NSString *)dataString logoImage:(UIImage *)logoImage imageSize:(CGFloat)size
{
    // 1. 创建一个二维码滤镜实例(CIFilter)
    CIFilter *filter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
    // 滤镜恢复默认设置
    [filter setDefaults];
    
    // 2. 给滤镜添加数据
    NSData *data = [dataString dataUsingEncoding:NSUTF8StringEncoding];
    // 使用KVC的方式给filter赋值
    [filter setValue:data forKeyPath:@"inputMessage"];
    
    // 3. 生成二维码
    CIImage *codeImage = [filter outputImage];
    
    
    return [self QRCodeUIImageFormCIImage:codeImage logoImage:logoImage withSize:size];
}
- (UIImage *)QRCodeUIImageFormCIImage:(CIImage *)image logoImage:(UIImage *)logoImage withSize:(CGFloat)size
{
    
    CGRect extent = CGRectIntegral(image.extent);
    CGFloat scale = MIN(size/CGRectGetWidth(extent), size/CGRectGetHeight(extent));
    
    // 1.创建bitmap;
    size_t width = CGRectGetWidth(extent) * scale;
    size_t height = CGRectGetHeight(extent) * scale;
    CGColorSpaceRef cs = CGColorSpaceCreateDeviceGray();
    CGContextRef bitmapRef = CGBitmapContextCreate(nil, width, height, 8, 0, cs, (CGBitmapInfo)kCGImageAlphaNone);
    CIContext *context = [CIContext contextWithOptions:nil];
    CGImageRef bitmapImage = [context createCGImage:image fromRect:extent];
    CGContextSetInterpolationQuality(bitmapRef, kCGInterpolationNone);
    CGContextScaleCTM(bitmapRef, scale, scale);
    CGContextDrawImage(bitmapRef, extent, bitmapImage);
    
    // 2.保存bitmap到图片
    CGImageRef scaledImage = CGBitmapContextCreateImage(bitmapRef);
    CGContextRelease(bitmapRef);
    CGImageRelease(bitmapImage);
    UIImage *newCodeImage = [UIImage imageWithCGImage:scaledImage];
    return [self addImage:newCodeImage logo:logoImage];
}
/**
 在一张图片上添加logo或者水印；
 warn 不支持jpg的图片
 
 @param image 原始的图片
 @param logoImage 要添加的logo
 @return 返回一张新的图片
 */
-(UIImage *)addImage:(UIImage *)image logo:(UIImage *)logoImage
{
    if (logoImage == nil)
    {
        return image;
    }
    //原始图片的宽和高，可以根据需求自己定义
    CGFloat w = image.size.width;
    CGFloat h = image.size.height;
    //logo的宽和高，也可以根据需求自己定义
    CGFloat logoWidth = w * 0.25;
    CGFloat logoHeight = h * 0.25;
    //绘制
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGContextRef context = CGBitmapContextCreate(NULL, w, h, 8, 444 * w, colorSpace, kCGImageAlphaPremultipliedFirst);
    CGContextDrawImage(context, CGRectMake(0, 0, w, h), image.CGImage);
    //绘制的logo位置,可自己调整
    CGContextDrawImage(context, CGRectMake((w - logoWidth)/2,(h - logoHeight)/2, logoWidth, logoHeight), [logoImage CGImage]);
    CGImageRef imageMasked = CGBitmapContextCreateImage(context);
    CGContextRelease(context);
    CGColorSpaceRelease(colorSpace);
    return [UIImage imageWithCGImage:imageMasked];
}
@end
